package AutoTest2018.utils.impl;

import AutoTest2018.utils.IHttpRequestUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class HttpClientUtil implements IHttpRequestUtil
{
    /***
     * 最普通的 get 请求
     * @param url 请求的地址
     * @return 请求的返回结果
     * @throws IOException
     */
    public String httpGet(String url) throws IOException
    {
        HttpGet get = new HttpGet(url);
        //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(get);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        return result;
    }

    /***
     * 带参数的 get 请求
     * @param url
     * @param params
     * @return 请求的返回结果
     * @throws IOException
     */
    public String httpGet(String url, Map<String, String> params) throws IOException
    {
        if (params == null)
        {
            return httpGet(url);
        }
        else
        {
            //生成 get 请求所需要的 参数
            List<NameValuePair> getParams = new ArrayList<NameValuePair>();
            Set<String> set = params.keySet();
            for (String key : set)
            {
                getParams.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParams);
            String str = EntityUtils.toString(entity);
            //执行 get 请求
            HttpGet httpGet = new HttpGet(url + "?" + str);
            HttpClient client = HttpClientBuilder.create().build();
            HttpResponse response = client.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            return result;
        }
    }

    /***
     * 不带参数，但需要带cookie的 get 请求
     * @param url  访问的地址
     * @param cookieStore  带的cookie
     * @return 请求的返回结果
     */
    public String httpGet(String url, CookieStore cookieStore) throws IOException
    {
        if (cookieStore == null)
        {
            return httpGet(url);
        }
        else
        {
            HttpGet get = new HttpGet(url);
            //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
            HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
            HttpResponse response = client.execute(get);
            String result = EntityUtils.toString(response.getEntity());
            return result;
        }
    }

    /***
     * 有参数，有cookie的 get 请求
     * @param url
     * @param params
     * @param cookieStore
     * @return
     * @throws IOException
     */
    public String httpGet(String url, Map<String, String> params, CookieStore cookieStore) throws IOException
    {
        if (params != null && cookieStore != null)
        {
            //生成 get 请求所需要的 参数
            List<NameValuePair> getParams = new ArrayList<NameValuePair>();
            Set<String> set = params.keySet();
            for (String key : set)
            {
                getParams.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParams);
            String str = EntityUtils.toString(entity);
            //执行 get 请求
            HttpGet httpGet = new HttpGet(url + "?" + str);
            HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
            HttpResponse response = client.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            return result;
        }
        else if (params == null && cookieStore != null)
        {
            return httpGet(url, cookieStore);
        }
        else if (params != null && cookieStore == null)
        {
            return httpGet(url, params);
        }
        else
        {
            return httpGet(url);
        }
    }

    /***
     * 最简单的一个post请求
     * @param url 请求地址
     * @return response body
     * @throws IOException
     */
    public String httpPostForm(String url) throws IOException
    {
        HttpPost post = new HttpPost(url);
        //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return result;
    }


    /***
     * form形式的 post 请求
     * @param url 请求地址
     * @param params 请求的参数，用hashmap来表示
     * @return response body
     */
    public String httpPostForm(String url, Map<String, String> params) throws IOException
    {
        if (params == null)
        {
            return httpPostForm(url);
        }
        else
        {
            HttpPost post = new HttpPost("url");
            //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
            HttpClient client = HttpClientBuilder.create().build();
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Set<String> set = params.keySet();
            for (String key : set)
            {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            return result;
        }
    }

    /***
     * form形式的 post 请求, 带 cookie
     * @param url  请求地址
     * @param params  请求的参数，用hashmap来表示
     * @param cookieStore cookie
     * @return response body
     * @throws IOException
     */
    public String httpPostForm(String url, Map<String, String> params, CookieStore cookieStore) throws IOException
    {
        if(params!=null&&cookieStore!=null)
        {
            List<NameValuePair> getParams = new ArrayList<NameValuePair>();
            Set<String> set = params.keySet();
            for (String key : set)
            {
                getParams.add(new BasicNameValuePair(key, params.get(key)));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParams,"UTF-8");
            //执行 post 请求
            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
            HttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity());
            return result;
        }
        else if(cookieStore==null&&params!=null)
        {
            return httpPostForm(url,params);
        }
        else if(params==null&&cookieStore==null)
        {
            return httpPostForm(url);
        }
        else
        {
            return "居然还真有这种情况";
        }
    }

    /***
     * 使用post方法的，请求体是json格式的 http请求
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public String httpPostJson(String url,Map<String, String> params) throws IOException
    {
        HttpPost post = new HttpPost("url");
        //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
        HttpClient client = HttpClientBuilder.create().build();
        //设置请求头
        post.setHeader("Content-Type", "application/json");
        //把入参转换成json格式的string
        JSONObject jsonObject=new JSONObject();
        Set<String> set = params.keySet();
        for (String key : set)
        {
            jsonObject.put(key,params.get(key));
        }
        String body=jsonObject.toJSONString();
        //设置请求体
        post.setEntity(new StringEntity(body));
        //获取返回信息
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return result;
    }

    /***
     * 使用post方法的，请求体是json格式的 http请求，还带上了cookie
     * @param url
     * @param params
     * @param cookieStore
     * @return
     * @throws IOException
     */
    public String httpPostJson(String url,Map<String, String> params,CookieStore cookieStore) throws IOException
    {
        HttpPost post = new HttpPost("url");
        //HttpClient client = new DefaultHttpClient();   过时，不推荐使用
        HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
        //设置请求头
        post.setHeader("Content-Type", "application/json");
        //把入参转换成json格式的string
        JSONObject jsonObject=new JSONObject();
        Set<String> set = params.keySet();
        for (String key : set)
        {
            jsonObject.put(key,params.get(key));
        }
        String body=jsonObject.toJSONString();
        //设置请求体
        post.setEntity(new StringEntity(body));
        //获取返回信息
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return result;
    }



    /***
     * 手动添加 cookie
     * @param cookie 用 hashmap的形式来表示cookie
     * @return
     */
    public CookieStore setCookieStore(Map<String, String> cookie)
    {
        System.out.println("----setCookieStore");
        CookieStore cookieStore = new BasicCookieStore();
        Set<String> set = cookie.keySet();
        for (String key : set)
        {
            BasicClientCookie cookieTemp = new BasicClientCookie(key, cookie.get(key));
/*            cookieTemp.setVersion(0);
            cookieTemp.setDomain("127.0.0.1");
            cookieTemp.setPath("/CwlProClient");*/
            cookieStore.addCookie(cookieTemp);
        }
        return cookieStore;
    }

}
